package com.glacier.cloud.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.glacier.framework.component.dto.response.Response;
import com.glacier.framework.component.dto.response.StatusCode;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

/**
 * date 2024-01-31 22:16
 *
 * @author glacier
 * @version 1.0
 */
@Configuration
public class SentinelConfig {


    @PostConstruct
    public void init() {
        BlockRequestHandler blockRequestHandler = (exchange, t) -> {
            // 自定义异常处理
            Response<String> response = Response.error(StatusCode.INTERNAL_SERVER_ERROR);

            return ServerResponse.status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(response));
        };

        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

}
